package com.nuaa.yupicturebackend.utils;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@Slf4j
public class WorkdayUtils {
	// 假设已初始化节假日和补班日数据（示例为2024年，需根据实际年份更新）
	private static final HashSet<String> VACATION_DAYS = new HashSet<>();
	private static final HashSet<String> WORK_DAYS = new HashSet<>();

	static {
		int year = LocalDateTime.now().getYear();
		List<Integer> list = Arrays.asList(year, year - 1);
		list.forEach(years -> {
			String holidayJson = WorkdayUtils.get("https://timor.tech/api/holiday/year/" + years + "/");
			log.error("请求一次");
			Map holidayMap = JSONUtil.toBean(holidayJson, Map.class);
			Map<String, Object> holiday = (Map<String, Object>) holidayMap.get("holiday");
			for (Map.Entry<String, Object> entry : holiday.entrySet()) {
				Map<String, Object> holidayInfo = (Map<String, Object>) entry.getValue();
				boolean isHoliday = (boolean) holidayInfo.get("holiday");
				if (isHoliday) {
					VACATION_DAYS.add((String) holidayInfo.get("date"));
				} else {
					WORK_DAYS.add((String) holidayInfo.get("date"));
				}
			}
		});
	}


	/**
	 * 获取上一个工作日
	 *
	 * @param date 基准日期
	 * @return 上一个工作日日期
	 */
	public static LocalDateTime getLastWorkday(LocalDateTime date) {
		LocalDateTime currentDate = LocalDateTimeUtil.beginOfDay(date);
		while (true) {
			currentDate = currentDate.minusDays(1);
			String dateStr = LocalDateTimeUtil.format(currentDate, "yyyy-MM-dd");

			// 判断是否为补班日（即使周末也算工作日）
			if (WORK_DAYS.contains(dateStr)) {
				return currentDate;
			}
			// 排除节假日或周末
			if (!VACATION_DAYS.contains(dateStr) && !LocalDateTimeUtil.isWeekend(currentDate)) {
				return currentDate;
			}
		}
	}

	/**
	 * 发送get请求
	 */
	private static String get(String url) {
		StringBuilder inputLine = new StringBuilder();
		String read;
		try {
			HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
			urlConnection.setReadTimeout(30 * 1000);
			urlConnection.setConnectTimeout(30 * 1000);
			urlConnection.setRequestProperty("Charset", "UTF-8");
			urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36)");
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
			while ((read = in.readLine()) != null) {
				inputLine.append(read);
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return inputLine.toString();
	}
}